package io.gitee.lglbc.easy.security.core.security;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.gitee.lglbc.easy.security.core.config.EasySecurityProperties;
import io.gitee.lglbc.easy.security.open.EasyLogin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.Map;
/**
 * @author 乐哥聊编程
 */
public class EasyLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private EasySecurityProperties easySecurityProperties;
    @Autowired
    private EasyLogin easyLogin;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), new TypeReference<>() {
            });
            String userName = map.get(getUsernameParameter());
            String passwd = map.get(getPasswordParameter());
            if (easySecurityProperties.isCaptchaEnable()) {
                easyLogin.checkCaptcha(map);
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, passwd);
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
